package com.yzl.frelink.entities;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import lombok.Data;

@Data
public class Fretish {
    String reqid;
    String content;

    String scopeType;
    String scope;

    String conditionType;
    String condition;
    String regularCondition;
    String event;

    String component;

    String timingType;
    String timing;
    String timeUnit;

    String response;
    String[] resList; // [xxx, yyy = zzz]

    String[] variables;
    List<String> inVars; // [A,B,C]
    List<String> outVars; // [D,E,F]

    public void splitVars() {
        inVars = new ArrayList<>();
        outVars = new ArrayList<>();
        for (String variable : variables) {
            if (isOutVar(this.response, variable)) {
                outVars.add(variable);
            } else {
                inVars.add(variable);
            }
        }
        this.resList = this.response.split("&");
        for (int i = 0; i < resList.length; i++) {
            resList[i] = resList[i].replaceAll("\\(*", "").replaceAll("\\)*", "").trim();
        }
    }

    private boolean isOutVar(String response, String var) {
        String regex = "\\b" + Pattern.quote(var) + "\\b";
        if (response == null || !Pattern.compile(regex).matcher(response).find()) {
            return false;
        }
        // 响应中变量非输出情况
        // 被用以赋值元素
        String pattern1 = "=+\\s*" + var;
        // 方法参数
        String pattern2 = ".*\\s*\\s*\\(\\s*(.*,\\s*)" + var + "\\)";
        // 蕴含条件
        String pattern3 = "\\(?.*" + var + ".*\\)?\\s*=>\\s*.*";
        if (!response.matches(pattern1) && !response.matches(pattern2) && !response.matches(pattern3)) {
            return true;
        }
        
        return false;
    }
    
    public String resolveRes(boolean boolType, boolean unsettable) {
        if (this.response == null || this.response.isEmpty()) {
            System.out.println("Warning: requirement " + this.reqid + " has empty response.");
            return "";
        }
        StringBuilder sb = new StringBuilder();
        return resolveResWithoutState();
        // if (boolType) {
        //     if (unsettable) {
        //         return "if ~" + this.response + "\n    disp('Error')\nend";
        //     } else {
        //         for (String var : this.outVars) {
        //             if (var.startsWith("enter_")) continue;
        //             Matcher matcher = Pattern.compile("[^!]" + var).matcher(this.response);
        //             if (matcher.find()) {
        //                 sb.append(var).append(" = true;\n");
        //             } else {
        //                 sb.append(var).append(" = false;\n");
        //             }
                        
        //         }
        //         return sb.toString().trim();
        //     }
        // } else {
        //     if (unsettable) {
        //         return "if " + this.response + "\n    disp('Error')\nend";
        //     } else {
        //         for (String var : this.outVars) {
        //             if (var.startsWith("enter_")) continue;
        //             Matcher matcher = Pattern.compile("[^!]" + var).matcher(this.response);
        //             if (matcher.find()) {
        //                 sb.append(var).append(" = false;\n");
        //             } else {
        //                 sb.append(var).append(" = true;\n");
        //             }
                        
        //         }
        //         return sb.toString().trim();
        //     }
        // }
    }

    public String resolveCond() {
        if (this.condition == null || this.condition.isEmpty()) {
            System.out.println("Warning: requirement " + this.reqid + " has empty condition.");
            return "";
        }
        String cond = this.condition;
        // 替换preBool为变量
        String preMode = "preBool\\s*\\(\\s*([a-zA-Z]|[0-9]|_)*\\s*,\\s*[^\\)]*\\s*\\)\\s*\\&*\\s*";
        Matcher preMatcher = Pattern.compile(preMode).matcher(cond);
        cond = preMatcher.replaceAll("");
        cond = cond.replaceAll("!", "~");
        cond = cond.replaceAll("\\&", "&&");
        cond = cond.replaceAll("\\|", "||");
        cond = cond.replaceAll("=", "==");
        // 去除多余括号
        while (cond.startsWith("(") && cond.endsWith(")")) {
            cond = cond.substring(1, cond.length() - 1).trim();
        }
        if(cond.startsWith("send_")) {
            cond = "send(" + cond.substring(5, cond.length()).trim() + ")";
        }
        if (cond.startsWith("receive_")) {
            cond = "receive(" + cond.substring(8, cond.length()).trim() + ")";
        }
        return cond;
    }

    public boolean checkPreBool() {
        if (this.condition == null || this.condition.isEmpty()) {
            return false; // 无条件
        }
        String preMode = "preBool\\s*\\(\\s*(([a-zA-Z]|[0-9]|_)*)\\s*,\\s*[^\\)]*\\)\\s*\\&*";
        Matcher preMatcher = Pattern.compile(preMode).matcher(this.condition);
        if (preMatcher.find()) {
            return true; // preBool转移规约
        }
        return false; // 其他情况
    }

    public String resolveResWithoutState() {
        StringBuilder sb = new StringBuilder();
        for (String res : this.resList) {
            res = res.trim();
            if (res.isEmpty() || res.startsWith("enter_")) continue;
            if (res.startsWith("send_")) {
                sb.append("send(").append(res.replace("send_", "")).append(");\n");
            } else if (res.contains("=")) {
                String[] parts = res.split("=");
                if (parts.length != 2) {
                    System.out.println("Warning: requirement " + this.reqid + " has invalid response: " + res);
                    continue;
                }
                String var = parts[0].trim();
                String val = parts[1].trim();
                if (val.equalsIgnoreCase("true") || val.equalsIgnoreCase("false")) {
                    sb.append(var).append(" = ").append(val.toLowerCase()).append(";\n");
                } else if (val.matches("-?\\d+(\\.\\d+)?")) { // 数值
                    sb.append(var).append(" = ").append(val).append(";\n");
                } else { // 字符串
                    sb.append(var).append(" = \"").append(val).append("\";\n");
                }
            } else { // 单变量，视为布尔变量赋值true
                String var = res.trim();
                if (var.startsWith("!")) {
                    var = var.substring(1).trim();
                    sb.append(var).append(" = false;\n");
                } else {
                    sb.append(var).append(" = true;\n");
                }
            }
        }
        return sb.toString().trim();
    }
}
